package com.example.myeventbus;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.os.Bundle;
import android.widget.Toast;

import com.example.myeventbus.databinding.ActivityMain2Binding;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity2 extends AppCompatActivity {
    ActivityMain2Binding bindings;
    boolean flag = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bindings = DataBindingUtil.setContentView(this, R.layout.activity_main2);
        bindings.mainsend.setOnClickListener(view -> EventBus.getDefault().post(new EventMessage("主线程消息")));
//        给这个页面注册
        bindings.intdata.setOnClickListener(view -> regist());
    }

    //该方法用来判断只注册一次EventBus防止重复点击崩溃
    public void regist() {
        if (flag) {
            EventBus.getDefault().register(this);
            flag = false;
        }

    }

    //    接受粘性消息
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void GetStickMsg(StickMsg stickMsg) {
        bindings.showdata.setText(stickMsg.name);
    }

    //解注册
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().removeAllStickyEvents();//移除所有粘性事件
        EventBus.getDefault().unregister(this);
    }
}